package org.jetlinks.protocol.official.mqtt.down.zigbeeGateway.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.protocol.official.ObjectMappers;
import org.jetlinks.protocol.official.TopicPayload;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author bingzhong
 * @Date 2024/12/31 13:43
 * @Description zigbee 网关 控制插座
 */
public class ZigbeeGatewayControlSocket {

    static ObjectMapper mapper = ObjectMappers.JSON_MAPPER;


    /**
     * {"fid":"9","method":"write","object":"device",
     * "param":{"changed":"true","epid":"0x01",
     * "id":"0xa4c138570739d932",
     * "name":"Onoff",
     * "value":["0x01"]}}
     * @param functionInvokeMessage
     * @param topicPatten
     * @return
     */
    @SneakyThrows
    public static TopicPayload encode(FunctionInvokeMessage functionInvokeMessage, String topicPatten) {


        String onOffStatus = String.valueOf(functionInvokeMessage
                                                    .getInput("onOffStatus")
                                                    .orElseThrow(() -> new IllegalArgumentException("onOffStatus not exists")));

        String topic = String.valueOf(functionInvokeMessage
                                                    .getInput("topic")
                                                    .orElseThrow(() -> new IllegalArgumentException("topic not exists")));


        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("fid", "123");
        dataMap.put("object", "device");
        dataMap.put("method", "write");
        Map<String, Object> paramMap = new HashMap<>();
//        paramMap.put("id", functionInvokeMessage.getDeviceId());
        paramMap.put("id", functionInvokeMessage.getDeviceId());
        paramMap.put("epid", "0x01");
        paramMap.put("name", "Onoff");
        List<String> valueList = new ArrayList<>();
        valueList.add(onOffStatus);
        paramMap.put("value", valueList);
        dataMap.put("param", paramMap);
        byte[] payloadBytes = mapper.writeValueAsBytes(dataMap);

        return TopicPayload.of(topic, payloadBytes);

    }

}
